import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:excel/excel.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/user_model.dart';
import '../models/student_model.dart';
import '../utils/file_util.dart';
import 'exam_service.dart';

class StudentService {
  static const String _studentDataKey = 'student_data';
  static List<Student> _students = [];
  static bool _isInitialized = false;

  // 初始化服务
  static Future<void> init() async {
    if (_isInitialized) return;
    
    try {
      await _loadStudents();
      _isInitialized = true;
    } catch (e) {
      debugPrint('初始化学生服务失败: $e');
      _students = [];
    }
  }

  // 从本地存储加载学生数据
  static Future<void> _loadStudents() async {
    final prefs = await SharedPreferences.getInstance();
    final studentsJsonString = prefs.getString(_studentDataKey);
    
    if (studentsJsonString != null) {
      final List<dynamic> studentsJson = jsonDecode(studentsJsonString);
      _students = studentsJson.map((json) => Student.fromJson(json)).toList();
    }
  }

  // 保存学生数据到本地存储
  static Future<bool> _saveStudents() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final studentsJsonString = jsonEncode(_students.map((s) => s.toJson()).toList());
      return await prefs.setString(_studentDataKey, studentsJsonString);
    } catch (e) {
      debugPrint('保存学生数据失败: $e');
      return false;
    }
  }

  /// 从Excel文件导入学生数据
  static Future<ImportResult> importFromExcel(File file) async {
    try {
      // 验证文件是否是Excel文件
      final fileName = file.path.toLowerCase();
      if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
        return ImportResult(
          success: false,
          message: '文件格式错误，请选择.xlsx或.xls格式的Excel文件',
        );
      }

      // 检查文件是否存在
      if (!await file.exists()) {
        return ImportResult(
          success: false,
          message: '文件不存在: ${file.path}',
        );
      }

      // 检查文件大小
      final fileSize = await file.length();
      if (fileSize == 0) {
        return ImportResult(
          success: false,
          message: '文件为空，无法导入',
        );
      }

      debugPrint('正在读取Excel文件: ${file.path}, 大小: $fileSize 字节');

      // 读取文件内容
      final bytes = await file.readAsBytes();
      
      // 尝试解析Excel文件
      Excel excel;
      try {
        excel = Excel.decodeBytes(bytes);
      } catch (e) {
        debugPrint('Excel解析错误: $e');
        return ImportResult(
          success: false,
          message: '无法解析Excel文件，文件可能已损坏: ${e.toString()}',
        );
      }

      if (excel.sheets.isEmpty) {
        return ImportResult(
          success: false,
          message: 'Excel文件不包含任何工作表',
        );
      }

      if (excel.sheets.values.first.maxRows < 2) {
        return ImportResult(
          success: false,
          message: 'Excel文件没有数据行',
        );
      }

      // 获取第一个工作表
      final sheet = excel.sheets.values.first;

      // 获取表头，确定列的位置
      final headers = _getExcelHeaders(sheet);
      
      // 验证必要的列是否存在
      if (!headers.containsKey('姓名') && !headers.containsKey('name')) {
        return ImportResult(
          success: false,
          message: '无法找到"姓名"或"name"列',
        );
      }
      
      if (!headers.containsKey('账号') && !headers.containsKey('account')) {
        return ImportResult(
          success: false,
          message: '无法找到"账号"或"account"列',
        );
      }
      
      if (!headers.containsKey('身份证号码') && !headers.containsKey('id')) {
        return ImportResult(
          success: false,
          message: '无法找到"身份证号"或"id"列',
        );
      }

      // 获取列索引
      final nameIndex = headers.containsKey('姓名') ? headers['姓名']! : headers['name']!;
      final accountIndex = headers.containsKey('账号') ? headers['账号']! : headers['account']!;
      final idIndex = headers.containsKey('身份证号码') ? headers['身份证号码']! : headers['id']!;

      // 读取数据行
      final students = <Student>[];
      int invalidCount = 0;
      final errors = <String>[];

      for (int i = 1; i < sheet.maxRows; i++) {
        try {
          final row = sheet.row(i);
          
          // 检查行是否有足够的单元格
          if (row.length <= max(nameIndex, max(accountIndex, idIndex))) {
            invalidCount++;
            errors.add('第${i + 1}行: 单元格数量不足');
            continue;
          }
          
          // 获取单元格值
          final name = _getCellValue(row[nameIndex]);
          final account = _getCellValue(row[accountIndex]);
          final id = _getCellValue(row[idIndex]);
          
          // 验证数据
          if (name.isEmpty || account.isEmpty || id.isEmpty) {
            invalidCount++;
            errors.add('第${i + 1}行: 姓名、账号或身份证号不能为空');
            continue;
          }
          
          // 添加学生记录
          students.add(Student(
            name: name,
            id: account,
            idCardNumber: id,
          ));
        } catch (e) {
          invalidCount++;
          errors.add('第${i + 1}行: 处理错误 - ${e.toString()}');
        }
      }
      
      // 检查是否有有效数据
      if (students.isEmpty) {
        return ImportResult(
          success: false,
          message: '没有有效的学生数据可导入',
          details: errors.join('\n'),
        );
      }
      
      // 更新学生列表
      _students = students;
      
      // 保存到本地存储
      await _saveStudents();
      
      // 构建结果消息
      String message = '成功导入${students.length}条学生记录';
      if (invalidCount > 0) {
        message += '，${invalidCount}条记录无效';
      }
      
      return ImportResult(
        success: true,
        message: message,
        details: invalidCount > 0 ? errors.join('\n') : null,
        importedCount: students.length,
      );
    } catch (e) {
      debugPrint('导入过程中发生错误: $e');
      String errorMessage = '导入过程中发生错误';
      
      if (e.toString().contains('Could not find End of Central Directory Record')) {
        errorMessage = '无法找到Excel文件的目录记录，文件可能已损坏或不是有效的Excel文件。请尝试重新创建Excel文件。';
      } else {
        errorMessage = '导入过程中发生错误: ${e.toString()}';
      }
      
      return ImportResult(
        success: false,
        message: errorMessage,
      );
    }
  }

  // 获取Excel表头并返回列名与索引的映射
  static Map<String, int> _getExcelHeaders(Sheet sheet) {
    final headers = <String, int>{};
    final row = sheet.row(0);
    
    for (int i = 0; i < row.length; i++) {
      final value = _getCellValue(row[i]);
      if (value.isNotEmpty) {
        headers[value] = i;
      }
    }
    
    return headers;
  }
  
  // 获取单元格的值并转换为字符串
  static String _getCellValue(dynamic cell) {
    if (cell == null) return '';
    
    if (cell is Data) {
      return cell.value?.toString() ?? '';
    }
    
    return cell.toString().trim();
  }

  // 手动添加学生
  static Future<ImportResult> addStudent(String name, String id, String idCardNumber) async {
    try {
      if (name.isEmpty || id.isEmpty || idCardNumber.isEmpty) {
        return ImportResult(success: false, message: '所有字段都必须填写');
      }
      
      // 检查ID是否重复
      if (_students.any((s) => s.id == id)) {
        return ImportResult(success: false, message: '学生账号已存在');
      }
      
      // 添加学生
      _students.add(Student(
        id: id,
        name: name,
        idCardNumber: idCardNumber,
        email: null,
        avatar: null,
      ));
      
      // 保存到本地存储
      final saved = await _saveStudents();
      
      if (!saved) {
        return ImportResult(success: false, message: '保存学生数据失败');
      }
      
      return ImportResult(
        success: true, 
        message: '成功添加学生 $name',
        importedCount: 1
      );
    } catch (e) {
      debugPrint('添加学生失败: $e');
      return ImportResult(success: false, message: '添加学生时发生错误: $e');
    }
  }
  
  // 批量添加学生示例
  static Future<ImportResult> addSampleStudents() async {
    try {
      // 清除现有数据
      _students.clear();
      
      // 添加示例学生
      _students.add(Student(
        id: 'zhangsan',
        name: '张三',
        idCardNumber: '110101199001011234',
        email: null,
        avatar: null,
      ));
      
      _students.add(Student(
        id: 'lisi',
        name: '李四',
        idCardNumber: '110101199101011234',
        email: null,
        avatar: null,
      ));
      
      _students.add(Student(
        id: 'wangwu',
        name: '王五',
        idCardNumber: '110101199201011234',
        email: null,
        avatar: null,
      ));
      
      // 保存到本地存储
      final saved = await _saveStudents();
      
      if (!saved) {
        return ImportResult(success: false, message: '保存学生数据失败');
      }
      
      return ImportResult(
        success: true, 
        message: '成功添加3名示例学生',
        importedCount: 3
      );
    } catch (e) {
      debugPrint('添加示例学生失败: $e');
      return ImportResult(success: false, message: '添加示例学生时发生错误: $e');
    }
  }

  // 获取Excel文件的固定存储路径
  static Future<String> getExcelFilePath() async {
    final directory = await getApplicationDocumentsDirectory();
    return '${directory.path}/学生信息导入.xlsx';
  }
  
  // 检查是否存在可导入的Excel文件
  static Future<bool> hasExcelFile() async {
    final path = await getExcelFilePath();
    final file = File(path);
    return file.exists();
  }
  
  // 生成Excel模板文件到固定路径
  static Future<String?> generateTemplateToPath() async {
    try {
      final excel = Excel.createExcel();
      final sheet = excel.sheets.keys.first;
      
      // 添加表头
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 0), '姓名');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 0), '账号');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 0), '身份证号码');
      
      // 添加示例数据
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 1), '张三');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 1), 'zhangsan');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 1), '110101199001011234');
      
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 2), '李四');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 2), 'lisi');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 2), '110101199101011234');
      
      // 确保目录存在
      final directory = await getApplicationDocumentsDirectory();
      final dirPath = '${directory.path}/StudentImport';
      final dir = Directory(dirPath);
      if (!await dir.exists()) {
        await dir.create(recursive: true);
      }
      
      // 保存Excel文件
      final path = '${dirPath}/students.xlsx';
      final file = File(path);
      await file.writeAsBytes(excel.encode()!);
      
      return path;
    } catch (e) {
      debugPrint('生成模板失败: $e');
      return null;
    }
  }

  // 生成Excel模板文件
  static Future<String?> generateTemplate() async {
    try {
      final excel = Excel.createExcel();
      final sheet = excel.sheets.keys.first;
      
      // 添加表头
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 0), '姓名');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 0), '账号');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 0), '身份证号码');
      
      // 添加示例数据
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 1), '张三');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 1), 'zhangsan');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 1), '110101199001011234');
      
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 2), '李四');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 2), 'lisi');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 2), '110101199101011234');
      
      // 保存Excel文件
      final directory = await getApplicationDocumentsDirectory();
      final path = '${directory.path}/学生信息导入模板.xlsx';
      final file = File(path);
      await file.writeAsBytes(excel.encode()!);
      
      return path;
    } catch (e) {
      debugPrint('生成模板失败: $e');
      return null;
    }
  }

  // 验证学生登录
  static bool validateLogin(String name, String idCardNumber) {
    if (!_isInitialized) {
      debugPrint('学生服务未初始化');
      return false;
    }
    
    // 如果没有导入学生数据，返回false
    if (_students.isEmpty) {
      debugPrint('没有导入学生数据');
      return false;
    }

    // 打印所有学生的身份证号码
    for (var student in _students) {
      debugPrint('身份证号码: ${student.idCardNumber}');
    }
    
    // 查找匹配的学生
    return _students.any((student) => 
      student.name == name && student.idCardNumber == idCardNumber
    );
  }
  
  // 获取学生列表
  static List<Student> getStudents() {
    return List.unmodifiable(_students);
  }
  
  // 清除所有学生数据
  static Future<bool> clearAllStudents() async {
    _students.clear();
    return await _saveStudents();
  }

  // 创建示例Excel文件，如果不存在的话
  static Future<String> createExampleExcelIfNeeded() async {
    final path = await getExcelFilePath();
    final file = File(path);
    
    // 检查文件是否已存在
    if (await file.exists()) {
      return path;
    }
    
    try {
      final excel = Excel.createExcel();
      final sheet = excel.sheets.keys.first;
      
      // 添加表头
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 0), '姓名');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 0), '账号');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 0), '身份证号码');
      
      // 添加示例数据
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 1), '张三');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 1), 'zhangsan');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 1), '110101199001011234');
      
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 2), '李四');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 2), 'lisi');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 2), '110101199101011234');
      
      // 保存到固定路径
      await file.create(recursive: true);
      await file.writeAsBytes(excel.encode()!);
      
      return path;
    } catch (e) {
      debugPrint('创建示例Excel文件失败: $e');
      return '';
    }
  }
  
  // 获取Excel导入文件的目录
  static Future<String> getExcelDirectory() async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  // 获取外部Excel目录
  static Future<String?> getExternalExcelDirectory() async {
    try {
      Directory? directory;
      
      // 尝试获取公共下载目录 (更容易被用户访问)
      if (Platform.isAndroid) {
        // 在Android上使用外部存储下载目录
        directory = Directory('/storage/emulated/0/Download/ExamApp');
      } else {
        // 在iOS和其他平台使用应用文档目录
        final appDocDir = await getApplicationDocumentsDirectory();
        directory = Directory('${appDocDir.path}/ExamApp');
      }
      
      // 确保目录存在
      if (!await directory.exists()) {
        await directory.create(recursive: true);
      }
      
      return directory.path;
    } catch (e) {
      debugPrint('获取外部Excel目录失败: $e');
      
      // 失败时回退到应用文档目录
      try {
        final directory = await getApplicationDocumentsDirectory();
        final excelDir = '${directory.path}/ExcelExport';
        
        // 确保目录存在
        final dir = Directory(excelDir);
        if (!await dir.exists()) {
          await dir.create(recursive: true);
        }
        
        return excelDir;
      } catch (e) {
        debugPrint('获取备用Excel目录也失败了: $e');
        return null;
      }
    }
  }
  
  // 确保Excel目录存在
  static Future<void> ensureExcelDirectoryExists() async {
    try {
      // 确保内部Excel目录存在
      final directory = await getApplicationDocumentsDirectory();
      final internalDir = Directory('${directory.path}/ExcelImport');
      if (!await internalDir.exists()) {
        await internalDir.create(recursive: true);
      }
      
      // 确保外部Excel目录存在
      final externalDir = await getExternalExcelDirectory();
      if (externalDir != null) {
        final externalDirectory = Directory(externalDir);
        if (!await externalDirectory.exists()) {
          await externalDirectory.create(recursive: true);
        }
      }
    } catch (e) {
      debugPrint('确保Excel目录存在失败: $e');
    }
  }

  // 生成导出的Excel模板到外部存储
  static Future<String?> generateTemplateToExternal() async {
    try {
      final externalDir = await getExternalExcelDirectory();
      if (externalDir == null) {
        return null;
      }
      
      final excel = Excel.createExcel();
      final sheet = excel.sheets.keys.first;
      
      // 添加表头
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 0), '姓名');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 0), '账号');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 0), '身份证号码');
      
      // 添加示例数据
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 1), '张三');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 1), 'zhangsan');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 1), '110101199001011234');
      
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 2), '李四');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 2), 'lisi');
      excel.updateCell(sheet, CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 2), '110101199101011234');
      
      // 保存Excel文件到外部存储
      final path = '$externalDir/学生信息导入模板.xlsx';
      final file = File(path);
      await file.writeAsBytes(excel.encode()!);
      
      return path;
    } catch (e) {
      debugPrint('生成外部模板失败: $e');
      return null;
    }
  }
  
  // 为学生分配随机考试
  static Future<void> assignRandomExamToStudent(String studentName, String studentId) async {
    try {
      // 获取随机考试
      final randomExam = ExamService.getRandomExamForStudent(studentId);
      if (randomExam == null) {
        debugPrint('没有可用的考试为学生 $studentName 分配');
        return;
      }
      
      // 查找学生并更新分配的考试ID
      final studentIndex = _students.indexWhere((s) => s.name == studentName && s.id == studentId);
      if (studentIndex != -1) {
        final oldStudent = _students[studentIndex];
        final updatedStudent = Student(
          id: oldStudent.id,
          name: oldStudent.name,
          idCardNumber: oldStudent.idCardNumber,
          email: oldStudent.email,
          avatar: oldStudent.avatar,
          assignedExamId: randomExam.id,
        );
        
        _students[studentIndex] = updatedStudent;
        await _saveStudents();
        
        debugPrint('已为学生 $studentName 分配考试: ${randomExam.title}');
      }
    } catch (e) {
      debugPrint('为学生分配考试失败: $e');
    }
  }
  
  // 获取学生分配的考试ID
  static String? getStudentAssignedExamId(String studentName, String studentId) {
    final student = _students.firstWhere(
      (s) => s.name == studentName && s.id == studentId,
      orElse: () => Student(id: '', name: '', idCardNumber: ''),
    );
    
    return student.id.isNotEmpty ? student.assignedExamId : null;
  }

  // 根据学生ID获取学生姓名
  static String? getStudentNameById(String studentId) {
    try {
      final student = _students.firstWhere(
        (s) => s.id == studentId,
        orElse: () => Student(id: '', name: '', idCardNumber: ''),
      );
      return student.id.isNotEmpty ? student.name : null;
    } catch (e) {
      debugPrint('根据ID获取学生姓名失败: $e');
      return null;
    }
  }

  // 根据学生ID获取学生对象
  static Student? getStudentById(String studentId) {
    try {
      final student = _students.firstWhere(
        (s) => s.id == studentId,
        orElse: () => Student(id: '', name: '', idCardNumber: ''),
      );
      return student.id.isNotEmpty ? student : null;
    } catch (e) {
      debugPrint('根据ID获取学生对象失败: $e');
      return null;
    }
  }
}

/// 导入结果类
class ImportResult {
  final bool success;
  final String message;
  final String? details;
  final int importedCount;
  
  ImportResult({
    required this.success, 
    required this.message,
    this.details,
    this.importedCount = 0
  });
} 